<template>
	<view class="order">
		<Navigation backType="back" title="我的订单" background="#fff" />
		<view class="background-white h-88 ph-20">
			<u-tabs :list="statusList" lineColor="#FABB3C"
				:activeStyle="{ fontSize: '28rpx', color: '#FABB3C', fontWeight: '600' }"
				:inactiveStyle="{ fontSize: '28rpx', color: '#222222' }" lineWidth="32rpx" lineHeight="4rpx"
				:itemStyle="{ width: '20%', height: '68rpx' }" keyName="label" :current="curt"
				@click="changeStatus"></u-tabs>
		</view>
		<!-- <view class="background-white ph-32 h-80">
        <view class="w-f h-60 search">
            <u-search
                placeholder="快速查找戳我"
                v-model="keyword"
                height="30"
                bgColor="#F5F5F5"
                searchIconColor="#999"
                placeholderColor="#999"
                clearabled
                :showAction="false"
            >
            </u-search>
            <view class="w-100 search-btn"><u-button text="搜索" color="#FABB3C" shape="circle" @click.stop="toSearch"></u-button></view>
        </view>
    </view> -->
		<scroll-view scroll-y="true" :style="{ height: height - 40 + 'px' }" :refresher-enabled="isOpenRefresh"
			:refresher-triggered="triggered" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
			@scrolltolower="scrolltolower">
			<view class="mt-20 background-white ph-32 pv-32" @click="toDetail(item)" v-for="(item, index) in list"
				:key="index">
				<view class="f ai-c jc-s-b">
					<view class="fs-24 text-color3">订单编号：{{ item.no }}</view>
					<view class="fs-24" :style="{ color: statusLists[item.status].color }">
						<text>{{statusLists[item.status].name}}</text>
					</view>
				</view>
				<view class="f mt-32" v-for="(iten, indexs) in item.items" :key="indexs">
					<image :src="iten.picUrl" class="w-160 h-160 b-12 mr-20"></image>
					<view class="f ai-c f1">
						<view class="f f1 mr-24 fd-c">
							<view class="fs-28 fw-600 text-color4"> {{ iten.spuName }}</view>
							<!-- <view class="fs-24 mt-8 text-color3">成都市武侯区科华南路1号</view> -->

							<view class="fs-26 fw-600 mt-20 text-color7">¥{{formater(iten.price)}} </view>

						</view>
						<view class="fs-24 text-color3">x{{ iten.count }}</view>
					</view>
				</view>
				<view class="f jc-f-e mt-32">
					<!-- status 0:待支付 10:待发货 20:已发货 30:已完成 40:已取消 -->
					<view class="w-152 h-64 b-64 f ai-c jc-c fs-26 text-color4 border ml-16"
						@click.stop="toAfterSales(item)" v-show="item.status == 30 ">申请售后
					</view>
					<view class="w-152 h-64 b-64 f ai-c jc-c fs-26 text-color4 border ml-16" v-show="item.status == 0"
						@click.stop="handleCancel(item)">取消
					</view>
					<view class="w-152 h-64 b-64 f ai-c jc-c fs-26 text-color border2 ml-16" v-show="item.status == 0"
						@click.stop="handlePay(item)">立即付款
					</view>
					<view class="w-152 h-64 b-64 f ai-c jc-c fs-26 text-color border2 ml-16" v-show=" item.status == 20"
						@click.stop="handleTakeOver(item)">收货
					</view>
					<view class="w-152 h-64 b-64 f ai-c jc-c fs-26 text-color border2 ml-16"
						v-show=" item.status == 20||item.status == 30" @click.stop="toWuli(item)">查询物流
					</view>
					<view class="w-152 h-64 b-64 f ai-c jc-c fs-26 text-color border2 ml-16"
						@click.stop="toEvaluate(item)" v-show=" item.status == 30&&!item.commentStatus">评价
					</view>
					<view class="w-204 h-64 b-64 f ai-c jc-c fs-26 text-color border2 ml-16" v-show="item.status == 1">
						修改服务时间
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>
<script setup lang="ts">
	import { ref } from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { dictDataType } from '@/services/api/dict';
	import { orderPage, orderSubmit, orderCancel, orderReceive } from '@/services/api/shop/order';
	import { useAuthStore } from '@/store/modules/auth';
	import { socialUser } from "@/services/api/index";
	import { formater } from '@/utils/global';

	const authStore = useAuthStore();
	const list = ref<any[]>([]);
	const curt = ref(0);
	const statusList = ref([]);
	const listParams = ref<any>({
		pageNo: 1,
		pageSize: 10,
		status: '',
	});
	const isOpenRefresh = ref(true);
	const openid = ref('');
	const triggered = ref(false);
	const statusLists = {
		'0': { name: '待付款', color: '#FE8C29' },
		'10': { name: '待发货', color: '#FE8C29' },
		'20': { name: '待收货', color: '#FE8C29' },
		'30': { name: '已完成', color: '#25B85B' },
		'40': { name: '已取消', color: '#999999' },
		'50': { name: '待评价', color: '#25B85B' },
	};
	onLoad(async (option : any) => {
		if (option.status) {
			curt.value = option.status
			listParams.value.status=option.status
		}
		listParams.pageNo = 1;
		getStatus();
		if (authStore.getOpenId) {
			openid.value = authStore.getOpenId
		} else {
			await getLogin()
		}
	});


	onShow(() => {
		list.value = [];
		listParams.value.pageNo = 1;
		getList();
	})
	function toWuli(item) {
		uni.navigateTo({
			url: '/pages_mine/orderWuLi?id=' + item.id

		})
	}
	//确认收货
	async function handleTakeOver(item : any) {
		uni.showModal({
			title: '提示',
			content: '确认收货？',
			success: async function (res) {
				if (res.confirm) {
					await orderReceive({ id: item.id });
					uni.showToast({
						title: '确认成功',
					});
					setTimeout(() => {
						list.value = [];
						listParams.value.pageNo = 1;
						getList();
					}, 1000);
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			},
		});
	}

	async function getLogin() {
		uni.login({
			provider: 'weixin',
			success: async (res) => {
				let result = await socialUser({ userID: authStore.getUserId, type: 10, state: '123', code: res.code });
				openid.value = result.data.openid
			},
		})
	}

	//取消订单
	async function handleCancel(item : any) {
		uni.showModal({
			title: '提示',
			content: '确认取消订单？',
			success: async function (res) {
				if (res.confirm) {
					await orderCancel(item.id);
					uni.showToast({
						title: '取消成功',
					});
					setTimeout(() => {
						list.value = [];
						listParams.value.pageNo = 1;
						getList();
					}, 1000);
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			},
		});
	}

	//立即支付
	async function handlePay(item : any) {
		const { data } = await orderSubmit({
			id: item.payOrderId,
			channelCode: 'wx_lite',
			channelExtras: { openid: openid.value }
		});
		let displayContent = JSON.parse(data.displayContent);
		await uni.requestPayment({
			provider: "wxpay",
			timeStamp: displayContent.timeStamp,
			nonceStr: displayContent.nonceStr,
			package: displayContent.packageValue,
			signType: displayContent.signType,
			paySign: displayContent.paySign,
			success(res2) {
				uni.showToast({
					title: '支付成功',
				});
				setTimeout(() => {
					list.value = [];
					listParams.value.pageNo = 1;
					getList();
				}, 1000);

			},
			fail(e) {
				console.log(e)
				uni.showToast({
					title: '支付失败,请重新支付',
					icon: 'none'
				})
			}
		})

	}

	//下拉刷新
	function onPulling(e : any) {
		if (e.detail.deltaY < 0) return;
		triggered.value = true;
	}

	function onRefresh() {
		triggered.value = false;
		list.value = [];
		listParams.value.pageNo = 1;
		getList();
	}

	//上拉加载
	function scrolltolower() {
		listParams.value.pageNo++;
		getList();
	}

	//切换状态
	function changeStatus(data : any) {
		curt.value = data.index;
		list.value = [];
		listParams.value.pageNo = 1;
		listParams.value.status = statusList.value[curt.value].value;
		getList();
	}

	//获取状态
	async function getStatus() {
		const { data } = await dictDataType({ type: 'order_status' });
		data.unshift({ label: '全部', value: '' });
		statusList.value = data;
		list.value = [];
		listParams.value.pageNo = 1;
		getList();
	}

	async function getList() {
		const { data } = await orderPage(listParams.value);
		list.value = list.value.concat(data.list);
	}

	function toDetail(data : any) {
		uni.navigateTo({
			url: `/pages_mine/orderDetail?id=${data.id}`,
		});
	}

	//售后
	function toAfterSales(item : any) {
		uni.navigateTo({
			url: `/pages_mine/afterSales?id=${item.id}`,
		});
	}

	//评价
	function toEvaluate(item : any) {
		uni.navigateTo({
			url: `/pages_mine/orderEvaluate?id=${item.id}`,
		});
	}

	let systemInfo = uni.getSystemInfoSync();
	const statusBarHeight = systemInfo.statusBarHeight;
	let pageHeight = systemInfo.windowHeight;
	const height = pageHeight - statusBarHeight - 46;
</script>
<style lang="scss" scoped>
	.order {
		background: #f5f5f5;
		min-height: 100vh;

		.border2 {
			border: 1rpx solid #fabb3c;
		}

		.border {
			border: 1rpx solid #dddddd;
		}

		.search {
			position: relative;

			.search-btn {
				position: absolute;
				right: 6rpx;
				top: 6rpx;
				z-index: 11;
			}

			::v-deep .u-button__text {
				font-size: 22rpx !important;
				font-weight: 400 !important;
			}

			::v-deep .u-button {
				height: 48rpx !important;
			}
		}

		.background-white {
			background: #fff;
		}
	}
</style>